$(function () {
  let $image = $('#image');
  const options = {
    aspectRatio: 1,
    preview: '.img-preview'
  };

  // 1.3 创建裁剪区域
  $image.cropper(options);

  $('#upload_avatar').click(function () {
    document.querySelector('#file').click();
  });

  //监听input框的选择
  $('#file').change((e) => {
    let fileList = e.target.files;
    console.log(fileList);
    let imgUrl = URL.createObjectURL(fileList[0]);
    console.log(imgUrl);

    //重新初始化裁切区域
    $image.cropper('destroy').attr('src', imgUrl).cropper(options);

    //更新头像
    $('#update_avatar').click(function () {
      let dataURL = $image
        .cropper('getCroppedCanvas', {
          // 创建一个 Canvas 画布
          width: 100,
          height: 100
        })
        .toDataURL('image/png');

      $.ajax({
        method: 'POST',
        url: '/my/update/avatar',
        data: {
          avatar: dataURL
        },
        success: function (res) {
          if (res.status !== 0) {
            return layer.msg('更换头像失败！');
          }
          layer.msg('更换头像成功！');
          window.parent.getUserInfo();
        }
      });
    });
  });
});
